//
//  MineEarlyTeachViewController.m
//  baodongPro
//
//  Created by feng on 16/3/6.
//  Copyright © 2016年 proper. All rights reserved.
//
#define welcomeString @"小朋友！欢迎你来到丫丫学堂，让我们愉快滴学习吧！little boys and girls! Welcome to YY school, let's learn it happily study!"

#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>
#import "MineEarlyTeachViewController.h"
#import "EarlyTeachCollectionCell.h"
#import "FamilyModel.h"

@interface MineEarlyTeachViewController()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,strong)UICollectionView * collectionView;
@property(nonatomic,strong) NSMutableArray* listMerberArray;
@property(nonatomic,assign) BOOL isOpenSelectTableView;
@end

@implementation MineEarlyTeachViewController
{
    NSArray< NSString*>* _soundValueArray;


    AVSpeechSynthesizer *avReader;
    AVSpeechUtterance *utterance;
    UIView* selectBackGroudView;
    UITableView* languageTableView;
    NSArray* _listLanguageArray;
    
    NSInteger _speakWithLanguageIndex;
    
}
-(void)viewDidLoad
{
    [super viewDidLoad];
    self.title=@"牙牙学语";
    _speakWithLanguageIndex=-99;
    _listLanguageArray=[self getAllLanguageModels];
    
    
    _listMerberArray=[NSMutableArray array];
    UIBarButtonItem* languageSelectButton=[[UIBarButtonItem alloc] initWithTitle:@"语言设置" style:UIBarButtonItemStylePlain target:self action:@selector(selectLangugePressed:)];
    self.navigationItem.rightBarButtonItem=languageSelectButton;
    
    
    _soundValueArray=@[@"爷爷",@"奶奶",@"外公",@"外婆",@"爸爸",@"妈妈",@"叔叔",@"阿姨",@"舅舅",@"舅妈",@"哥哥",@"姐姐",@"弟弟",@"妹妹"];
    [_soundValueArray enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
       
        FamilyModel* everyModel=[[FamilyModel alloc] init];
        everyModel.m_name=obj;
        [_listMerberArray addObject:everyModel];
        
    }];
    
    UICollectionViewFlowLayout*viewLayout=[[UICollectionViewFlowLayout alloc] init];

    [viewLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal]; //水平滑动
    [viewLayout setScrollDirection:UICollectionViewScrollDirectionVertical]; //控制滑动分页用
    viewLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);

    _collectionView=[[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, NeedViewHeight) collectionViewLayout:viewLayout];
    _collectionView.backgroundColor=[UIColor whiteColor];
    _collectionView.delegate=self;
    _collectionView.dataSource=self;
    _collectionView.showsHorizontalScrollIndicator=YES;
    [_collectionView registerClass:[EarlyTeachCollectionCell class] forCellWithReuseIdentifier:@"collectionCells"];
    [self.containedView addSubview:_collectionView];
    [self setUpRightSelectLanguageTableView];
//    _speakWithLanguageIndex=
    [self readCellTitle:welcomeString];
}

-(void)setUpRightSelectLanguageTableView
{
    selectBackGroudView=[self.view fbd_quickCreateUIViewWithFrame:CGRectMake(ScreenW, 0, 0, 0)];
    selectBackGroudView.backgroundColor=[UIColor blackColor];
    selectBackGroudView.alpha=0.9;
    languageTableView=[self.view fbd_quickCreateUITabdWithleViewFrame:CGRectMake(0, 0, screenW, NeedViewHeight) andDelegateAndDataSource:self];
    
    UILabel* tipLabel=[self.view fbd_quickCreateUILabelWithFrame:CGRectMake(0, 0, screenW, 100)];
    tipLabel.textColor=[UIColor redColor];
    tipLabel.backgroundColor=[UIColor whiteColor];
    tipLabel.numberOfLines=0;
    tipLabel.text=@"用户须知： \n 识别汉字需要以：ZH 开头的语言，其他的语言是不能识别汉字的，如果是英语可以用任何语言！望须知！";
    languageTableView.tableHeaderView=tipLabel;
    
    [languageTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"languageCells"];
    [selectBackGroudView addSubview:languageTableView];
    [self.containedView addSubview:selectBackGroudView];

}
-(void)setIsOpenSelectTableView:(BOOL)isOpenSelectTableView
{
    _isOpenSelectTableView=isOpenSelectTableView;
    
    if (_isOpenSelectTableView)
    {
        [self showOpenSelectLanguageTableView];
        
        
    }else
    {
        [self closeOpenSelectLanguageTableView];
        
    }



}

// 展开 select Language TableView
-(void)showOpenSelectLanguageTableView
{

    [UIView animateKeyframesWithDuration:0.3 delay:0 options:UIViewKeyframeAnimationOptionBeginFromCurrentState animations:^{
        
        [selectBackGroudView setFrame:self.containedView.bounds];
        
    } completion:nil];



}
// 收缩 select Language TableView
-(void)closeOpenSelectLanguageTableView
{

    [UIView animateKeyframesWithDuration:0.3 delay:0 options:UIViewKeyframeAnimationOptionBeginFromCurrentState animations:^{
        
        [selectBackGroudView setFrame:CGRectMake(screenW, 0, 0, 0)];
        
    } completion:nil];



}








#pragma mark ------------Event-------------------------
-(void)selectLangugePressed:(id)sender
{
    self.isOpenSelectTableView=!self.isOpenSelectTableView;
}

#pragma mark ------------ UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString* identifier=@"collectionCells";

    EarlyTeachCollectionCell* cell=[collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    cell.backgroundColor = [cell randomColor];
    
    FamilyModel* indexFamilyModel=[_listMerberArray objectAtIndex:indexPath.row];
    cell.v_FootNameLabel.text=indexFamilyModel.m_name;
    
    return cell;

}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{

    return _listMerberArray.count;

}



//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(ScreenW-20, (NeedViewHeight)/2.0-10);
}
//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(5, 10, 5, 10);
}
#pragma mark --UICollectionViewDelegate
//UICollectionView被选中时调用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
//    UICollectionViewCell * cell = (UICollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];

    NSInteger row=indexPath.row;
    FamilyModel*indexModel=[_listMerberArray objectAtIndex:row];
    NSString* rowTip=indexModel.m_name;
    
    [self readCellTitle:rowTip];

    
}

-(void)readCellTitle:(NSString*)cellString
{
    if (!avReader)
    {
      avReader=[[AVSpeechSynthesizer alloc] init];
    }
    if ([avReader continueSpeaking])
    {
        [avReader stopSpeakingAtBoundary:AVSpeechBoundaryImmediate];
    }

    utterance = [[AVSpeechUtterance alloc]initWithString:cellString]; //需要转换的文本
    //test 汉字和英语的区别
    //utterance = [[AVSpeechUtterance alloc]initWithString:@"good moring every one  ! i miss you !"];
    utterance.rate=0.4;
    if (_speakWithLanguageIndex>0)
    {
    AVSpeechSynthesisVoice* indexModel= [_listLanguageArray objectAtIndex:_speakWithLanguageIndex];
    utterance.voice=[AVSpeechSynthesisVoice voiceWithLanguage:indexModel.language];
    }

    NSLog(@"当前的是：%@",[AVSpeechSynthesisVoice currentLanguageCode]);
    [avReader speakUtterance:utterance];
    
    
}




#pragma  mark TableViewDelegate&&UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{


    return _listLanguageArray.count;


}

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell* cell=[tableView dequeueReusableCellWithIdentifier:@"languageCells"];
    NSInteger row=indexPath.row;
    
   AVSpeechSynthesisVoice* indexModel= [_listLanguageArray objectAtIndex:row];
   NSString* tip=[NSString stringWithFormat:@"%@---%@",    indexModel.language ,indexModel.name];

    if (row==_speakWithLanguageIndex)
    {
        tip=[NSString stringWithFormat:@"%@             默认<😄>语言",tip];
                cell.backgroundColor=[UIColor redColor];
    }else{
        cell.backgroundColor=[UIColor grayColor];
    }
    
    cell.textLabel.text=tip;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSInteger row=indexPath.row;
    _speakWithLanguageIndex=row;
    self.isOpenSelectTableView=!self.isOpenSelectTableView;

    [tableView reloadData];
    
    
}
-(NSArray<AVSpeechSynthesisVoice*>*)getAllLanguageModels
{
    NSArray * tesA=[AVSpeechSynthesisVoice speechVoices];
    [tesA enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        AVSpeechSynthesisVoice*objes=  (AVSpeechSynthesisVoice*)obj;
        NSLog(@">>>>>>%@  %@",objes.language, objes.language);
        
    }];
    return tesA;
}




@end
